package com.iot.manager.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.button.MaterialButton;
import com.iot.manager.R;
import com.iot.manager.data.models.Device;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.ui.adapters.DeviceAdapter;
import com.iot.manager.ui.activities.DeviceDetailActivity;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DevicesFragment extends Fragment implements DeviceAdapter.OnDeviceClickListener {
    private RecyclerView recyclerView;
    private DeviceAdapter deviceAdapter;
    private ApiService apiService;
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout errorLayout;
    private TextView errorText;
    private MaterialButton btnRetry;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_devices, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化视图
        recyclerView = view.findViewById(R.id.recycler_view);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        errorLayout = view.findViewById(R.id.error_layout);
        errorText = view.findViewById(R.id.errorText);
        btnRetry = view.findViewById(R.id.btn_retry);
        
        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        deviceAdapter = new DeviceAdapter(getContext(), this);
        recyclerView.setAdapter(deviceAdapter);
        
        // 设置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadDevices);
        
        // 设置重试按钮
        btnRetry.setOnClickListener(v -> loadDevices());
        
        // 初始化API服务
        apiService = RetrofitClient.getInstance().getApiService();
        
        // 加载数据
        loadDevices();
    }

    private void loadDevices() {
        showLoading(true);
        apiService.getDevices().enqueue(new Callback<List<Device>>() {
            @Override
            public void onResponse(Call<List<Device>> call, Response<List<Device>> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null) {
                    deviceAdapter.setDevices(response.body());
                    showError(false, null);
                } else {
                    showError(true, "获取设备列表失败");
                }
            }

            @Override
            public void onFailure(Call<List<Device>> call, Throwable t) {
                showLoading(false);
                showError(true, "网络错误：" + t.getMessage());
            }
        });
    }

    private void showLoading(boolean show) {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(show);
        }
    }

    private void showError(boolean show, String message) {
        if (errorLayout != null) {
            errorLayout.setVisibility(show ? View.VISIBLE : View.GONE);
        }
        if (errorText != null && message != null) {
            errorText.setText(message);
        }
        if (recyclerView != null) {
            recyclerView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void onDeviceClick(Device device) {
        if (getActivity() != null) {
            Intent intent = new Intent(getActivity(), DeviceDetailActivity.class);
            intent.putExtra("deviceId", device.getDeviceId());
            startActivity(intent);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (deviceAdapter != null) {
            deviceAdapter.onDestroy();
        }
    }
} 